package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.domain.EmployeeRole;
import cn.wolfcode.rbac.domain.query.EmployeeQueryObject;
import cn.wolfcode.rbac.domain.vo.AdminStateVo;
import cn.wolfcode.rbac.domain.vo.EmployeeRoleVo;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.mapper.EmployeeRoleMapper;
import cn.wolfcode.rbac.service.IEmployeeRoleService;
import cn.wolfcode.rbac.service.IEmployeeService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {
    @Resource
    private EmployeeRoleMapper employeeRoleMapper;
    @Resource
    private IEmployeeRoleService employeeRoleService;
    @Override
    public IPage<Employee> selectEmployeeByPage(EmployeeQueryObject qo) {
        IPage<Employee> page = new Page<>(qo.getPageNum(), qo.getPageSize());
        QueryWrapper<Employee> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.hasText(qo.getKeyword()),"name",qo.getKeyword());
        wrapper.like(qo.getDeptId()!=null,"dept_id",qo.getDeptId());
        return super.page(page,wrapper);
    }

    @Override
    public void saveOrUpdateEmployee(EmployeeRoleVo employeeRoleVo) {
        Employee employee = employeeRoleVo.getEmployee();
        List<Long> roleIds = employeeRoleVo.getRoleIds();
        Long id = employee.getId();
        if(id != null) {
            QueryWrapper<EmployeeRole> employeeRoleQueryWrapper = new QueryWrapper<>();
            employeeRoleQueryWrapper.eq("employee_id",id);
            employeeRoleMapper.delete(employeeRoleQueryWrapper);
            super.updateById(employee);
        } else {
            super.save(employee);
        }
        List<EmployeeRole> employeeRoles = new ArrayList<>();
        for (Long roleId : roleIds) {
            EmployeeRole employeeRole = new EmployeeRole();
            employeeRole.setEmployeeId(id);
            employeeRole.setRoleId(roleId);
            employeeRoles.add(employeeRole);
        }
        employeeRoleService.saveBatch(employeeRoles);
    }

    @Override
    public void updateStateById(AdminStateVo adminStateVo) {
        UpdateWrapper<Employee> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",adminStateVo.getId());
        wrapper.set("admin",adminStateVo.isAdmin());
        super.update(wrapper);
    }
}
